;;; python.cfg.el --- Summary
;;; Commentary:
;;; python configuration
;;; Code:
(require 'package.cfg)

(setq to-install
      '(jedi-core virtualenvwrapper traad pyenv-mode sphinx-doc company-jedi))
(mapc 'package-install-if-absent to-install)

(defun my-jedi:setup-hook ()
  "Custom jedi setup hook.
Set up custom jedi:environment-root and install server if needed."
  (setq jedi:environment-root "jedi")
  (unless (file-exists-p
           ;; This is ugly, but it's the only way I've found so far
           ;; to make file-exists-p deal with nil.
           (or (python-environment-bin "jediepcserver" jedi:environment-root)
               ;; Hopefully a file named like this won't exist.
               (number-to-string (abs (random)))))
    (message "Jedi virtual env not found. Installing it.")
    (jedi:install-server-block))
  ;; Code yanked from jedi:install-server-block
  ;; I have to do this or for some reason jedi:environment-root will not work.
  (setq-default jedi:server-command (jedi:-env-server-command))
  (jedi:setup))

(use-package python
  :init
  (add-hook 'python-mode-hook 'flyspell-prog-mode)
  (add-hook 'python-mode-hook 'yas-minor-mode)
  (add-hook 'python-mode-hook 'my-jedi:setup-hook)
  (add-hook 'python-mode-hook 'flycheck-mode)
  (add-hook 'python-mode-hook 'hs-minor-mode)
  (add-hook 'python-mode-hook 'sphinx-doc-mode)
  (setq python-indent-guess-indent-offset nil)
  :mode ("\\.py\\'" . python-mode)
  :interpreter ("python" . python-mode))

(use-package jedi-core
  :config
  (setq jedi:use-shortcuts t)
  (define-key jedi-mode-map (kbd "M-?") 'jedi:show-doc)
  (define-key jedi-mode-map (kbd "M-r") 'helm-jedi-related-names)
  :diminish jedi-mode)

;; client-server for the rope refactoring library.
(use-package traad
  :bind (("C-x t o" . traad-open)
         ("C-x t k" . traad-close)
         ("C-x t U" . traad-undo)
         ("C-x t Y" . traad-redo)
         ("C-x t r" . traad-rename)
         ("C-x t n" . traad-normalize-arguments)
         ("C-x t x" . traad-remove-argument)
         ("C-x t M" . traad-extract-method)
         ("C-x t V" . traad-extract-variable)
         ("C-x t f" . traad-findit)
         ("C-x t c" . traad-display-occurrences)
         ("C-x t i" . traad-display-implementations)
         ("C-x t d" . traad-goto-definition)))

(use-package pyenv-mode)

(use-package sphinx-doc
  :config
  (define-key sphinx-doc-mode-map (kbd "C-c M-d") nil)
  :bind ("C-c C-d" . sphinx-doc)
  :diminish sphinx-doc-mode)

(use-package virtualenvwrapper
  :config
  (progn
    (venv-initialize-interactive-shells)
    (venv-initialize-eshell)))

(use-package company-jedi
  :config
  (add-to-list 'company-backends 'company-jedi))

(provide 'python.cfg)
;;; python.cfg.el ends here
